#!/usr/bin/python
import sys, os

if len(sys.argv) != 2:
    print "Usage: %s Threads_connected | Threads_running | conn_pool" % str(sys.argv[0])
    sys.exit(4)
key = sys.argv[1].strip()

if not os.path.isdir("/opt/sql"):
    print 0
    sys.stderr.write("Service MySQL is not configured in this node")
    sys.exit(1)

import MySQLdb
try:
    conn = MySQLdb.connect(host='localhost', user='root', passwd='xAVa6Aze', port=3306)
except Exception, emsg:
    print 0
    sys.stderr.write("MySQL DB connection exception - " + str(emsg))
    sys.exit(1)

globalStats = {}
result = None

if key == 'Threads_connected' or  key == 'Threads_running':
    try:
        cursor = conn.cursor()
        cursor.execute("SHOW /*!50002 GLOBAL */ STATUS where Variable_name in ('Threads_connected', 'Threads_running')")
        result = cursor.fetchall()
        cursor.close()
        for row in result:
            globalStats[row[0]] = row[1]
   
        if key in globalStats.keys():
            print globalStats[key]
        else:
            print 0
            sys.stderr.write("MySQL key %s not found" % key)
            sys.exit(1)
    except Exception, emsg:
        print 0
        cursor.close()
        conn.close()
        sys.stderr.write("MySQL query exception - " + str(emsg))
        sys.exit(1)
elif key == 'conn_pool':
    pool = {}
    config = "/etc/snmp/mysql_config.txt"
    try:
        f = open(config)
        for line in f:
            line = line.strip()
            if line.startswith("#"):
                continue
            if line.count(":") == 3 :
                server, hostname, db, count = line.split(":")
                server = server.strip()
                db = db.strip()
                count = count.strip()
                if count == 'NA':
                    continue
                if server not in pool.keys():
                    pool[server] = {}
                #print pool
                pool[server][db] = count
        f.close()
    except Exception, emsg:
        print 0
        sys.stderr.write(str(emsg))
        sys.exit(1)

    try:
        cursor = conn.cursor()
        cursor.execute("select substring_index(host,':',1) as source ,db, count(db) from information_schema.processlist group by source,db;")
        result = cursor.fetchall()
        if cursor: cursor.close()
        if conn: conn.close()
    except Exception, emsg:
        print 0
        sys.stderr.write("MySQL query exception - " + str(emsg))
        if cursor: cursor.close()
        if conn: conn.close()
        sys.exit(1)

    try:
        prct_usage = 0
        for server,db,count in result:
            if server in pool.keys() and db in pool[server].keys():
                pool_max_hash = pool[server]
                #prct = round((count * 100)/ float(pool_max_hash[db]), 2)
                prct = (count * 100)/ int(pool_max_hash[db])
                if (prct > prct_usage):
                    prct_usage = prct
        print prct_usage
    except Exception, msg:
        print 0
        sys.stderr.write(str(msg))
        sys.exit(1)

sys.exit(0)